﻿using System.Net.WebSockets;
using System.Text;

namespace Wallpaper.Services.Socket
{
    public static class WebSocketService
    {
        // 使用字典存储每个用户的 WebSocket 连接
        private static readonly Dictionary<string, WebSocket> _userSockets = new Dictionary<string, WebSocket>();

        // 处理 WebSocket 连接
        public static async Task HandleWebSocketAsync(WebSocket socket, string userId)
        {
            // 将用户的 WebSocket 连接与用户 ID 映射
            _userSockets[userId] = socket;
            var buffer = new byte[1024 * 4];

            try
            {
                while (socket.State == WebSocketState.Open)
                {
                    var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        _userSockets.Remove(userId);  // 连接关闭时移除该用户
                        await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"WebSocket error for user {userId}: {ex.Message}");
            }
        }

        // 向特定用户发送消息
        public static async Task SendMessageToUserAsync(string userId, string message)
        {
            if (_userSockets.ContainsKey(userId))
            {
                var socket = _userSockets[userId];
                if (socket.State == WebSocketState.Open)
                {
                    var buffer = Encoding.UTF8.GetBytes(message);
                    var segment = new ArraySegment<byte>(buffer);
                    await socket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
                }
            }
        }

        // 可选：广播消息给所有连接（如果需要）
        public static async Task BroadcastMessageAsync(string message)
        {
            var buffer = Encoding.UTF8.GetBytes(message);
            var segment = new ArraySegment<byte>(buffer);

            foreach (var socket in _userSockets.Values)
            {
                if (socket.State == WebSocketState.Open)
                {
                    await socket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
                }
            }
        }
    }




}
